import re

import requests
import json

from Mode.Log import Log
from Mode.SQLiteMode import SQLite
from Mode.Example import Example
import datetime
from lxml import etree



def GetFundJsonInfo(fundcode):
	# 获取实时净值 2021/12/12 17:44 By Wangxc_a_bj
	url = "http://fundgz.1234567.com.cn/js/" + fundcode + ".js"
	response = requests.get(url)
	fundDataInfo = response.text.split('({')[1]
	fundDataInfo = '{' + fundDataInfo.split('})')[0] + '}'
	fundDataInfo = json.loads(fundDataInfo)
	return fundDataInfo


def GetlsjzInfo(fundcode, page=None, per=None, sdate=None, edate=None):
	# 获取历史净值 2021/12/12 17:43 By Wangxc_a_bj
	Tag = "GetlsjzInfo"
	url = f"https://fundf10.eastmoney.com/F10DataApi.aspx?type=lsjz&code={fundcode}"
	if page:
		url += f"&page={page}"
	if per:
		url += f"&per={per}"
	else:
		per = 10
	if sdate:
		url += f"&sdate={sdate}"
	if edate:
		url += f"&edate={edate}"
	response = requests.get(url)
	# print(response.text)
	table = re.match('.*"(.*)"', response.text)
	# print(table.group(1))
	html = etree.HTML(table.group(1))
	html_data = html.xpath('/html/body/table/tbody/tr/td')
	# print(html_data)
	res = []
	for i in range(1,per):
		# print(i)
		data = html.xpath(f'/html/body/table/tbody/tr[{i}]/td')
		# for j in data:
		# 	print(j.text)
		temp = data[0].text,data[1].text,data[2].text,data[3].text,data[4].text,data[5].text,data[6].text
		res.append(temp)
	Log(Tag,res)
	return res
		# date = data[0]
		# dwjz = data[0]


# def task():
# 	vaules = SQLite("Data.db").select("fund_information")
# 	print(vaules)
# 	for i in vaules:
# 		code = i[2]
# 		fundDataInfo = GetFundJsonInfo(code)
# 		print(fundDataInfo)
# 	sqlite = SQLite("Data.db")
# 	time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 	print(time)
# 	sql = f"UPDATE fund_valuation SET valuation = '{fundDataInfo['gsz']}',update_time = '{time}',price_latest= '{fundDataInfo['dwjz']}',last_date= '{fundDataInfo['jzrq']}',gszzl= '{fundDataInfo['gszzl']}' WHERE fund_id = '{code}'"
# 	print(sql)
# 	# sqlite.update(sql)
# 	# sql = f"UPDATE fund_information SET price_latest = '{fundDataInfo['dwjz']}',update_time = '{time}' WHERE fund_id = '{code}'"
# 	sqlite.update(sql)
# 	del sqlite
#
#
# # while True:
# # task()
GetlsjzInfo("003096")
